# -*- coding: utf-8 -*-
import hashlib
import json

import requests
import xmltodict
from django.conf import settings

from async import async_job
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://106.75.10.109/pay/make-order'
_QUERY_GATEWAY = 'http://106.75.10.109/pay/query-order'

# 北京行泽启科技有限公司
# 商户名：bjxingzeqikeji
# 商户ID：100046
# 商户KEY：6b1644ece3c51c54840fa733f0375a6e
# 初始密码：123456
# 威信和qq
APP_CONF = {
    '100046': {
        'API_KEY': '6b1644ece3c51c54840fa733f0375a6e'
    },
}


def _get_pay_type(service):
    if service == 'alipay':
        return 'ALIH5'
    elif service == 'wxpay':
        return 'WXH5'
    elif service == 'qq':
        return 'QQH5'
    elif service == 'jd':
        return 'JDH5'
    else:
        return 'WXH5'


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("jiuyingpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def dict_to_xml_str(tag, d):
    parts = ['<{}>'.format(tag)]
    for key, val in d.items():
        parts.append('<{0}>{1}</{0}>'.format(key, val))
    parts.append('</{}>'.format(tag))
    return ''.join(parts)


def generate_sign(parameter, key):
    '''  生成下单签名 '''
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k] != '' and parameter[k] != None:
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def _get_sdk_type(sdk_version):
    if 'android' in sdk_version.lower():
        return 'AND_WAP'
    else:
        return 'iOS_WAP'


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    key = _get_api_key(app_id)
    service = info.get('service')
    sdk_type = info.get('sdk_version')
    p_dict = {
        'pay_type': _get_pay_type(service),
        'mch_id': app_id,
        'out_trade_no': str(pay.id),
        'body': 'charge',
        'total_fee': int(pay_amount * 100),
        'mch_create_ip': _get_device_ip(info),
        'notify_url': '{}/pay/api/{}/jiuyingpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id),
        'callback_url': '{}/pay/api/{}/jiuyingpay/{}/'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id),
        'nonce_str': '233123123',
        'device_info': _get_sdk_type(sdk_type),
        'mch_app_name': 'qiuqiu',
        'mch_app_id': settings.NOTIFY_PREFIX,
    }
    p_dict['sign'] = generate_sign(p_dict, key)
    xml = dict_to_xml_str('xml', p_dict)
    _LOGGER.info("jiuyingpay create data: %s", p_dict)
    headers = {'Content-Type': 'application/xml;charset=utf-8'}
    response = requests.post(_GATEWAY, data=xml, headers=headers, timeout=10)
    _LOGGER.info("jiuyingpay create rsp data: %s", response.text)
    d = xmltodict.parse(response.text)
    return {'charge_info': d['xml']['pay_info']}


# SUCCESS
def check_notify_sign(request, app_id):
    key = _get_api_key(app_id)
    _LOGGER.info("jiuyingpay notify data: %s", request.body)
    data = xmltodict.parse(request.body)['xml']
    verify_notify_sign(data, key)
    pay_id = data['out_trade_no']
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s" % data)
        raise ParamError('jiuyingpay event does not contain valid pay ID')

    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = data['pay_result']
    trade_no = data.get('transaction_id')
    total_fee = float(data['total_fee']) / 100.0

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 'SUCCESS':
        _LOGGER.info('jiuyingpay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pass
    # pay_id = pay_order.id
    # key = _get_api_key(app_id)
    # p_dict = {
    #     'parter': app_id,
    #     'orderid': str(pay_id),
    # }
    # p_dict['sign'] = generate_query_sign(p_dict, key)
    # response = requests.get(_QUERY_GATEWAY.format(p_dict['orderid'], p_dict['parter'], p_dict['sign']))
    # _LOGGER.info(u'jiuyingpay create charge: %s', response.text)
    # data = json.loads(response.text)
    # if response.status_code == 200:
    #     trade_status = int(data['opstate'])
    #     total_fee = float(data['ovalue'])
    #     trade_no = ''
    #     extend = {
    #         'trade_status': trade_status,
    #         'trade_no': trade_no,
    #         'total_fee': total_fee
    #     }
    #
    #     if trade_status == 0:
    #         _LOGGER.info('jiuyingpay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
    #         res = add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
    #         if res:
    #             async_job.notify_mch(pay_order.id)
    # else:
    #     _LOGGER.warn('jiuyingpay data error, status_code: %s', response.status_code)

# if __name__ == '__main__':
#     p_dict = {
#         'mch_id': '100046',
#         'out_trade_no': '1628241844280229888',
#         'transaction_id': '151641837901018118372',
#         'nonce_str': '233123123',
#     }
#     p_dict['sign'] = generate_sign(p_dict, '6b1644ece3c51c54840fa733f0375a6e')
#     xml = dict_to_xml_str('xml', p_dict)
#     print xml
#     headers = {'Content-Type': 'application/xml;charset=utf-8'}
#     response = requests.post(_QUERY_GATEWAY, data=xml, headers=headers, timeout=10)
#     print response.text
#     print response.url
